package blue.http.internal.core.message;

import blue.http.core.message.View;
import blue.http.core.message.ViewBuilder;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建页面渲染对象
 *
 * @author zhengjin
 * @since 1.0 2018年03月16日
 */
public class DefaultViewBuilder implements ViewBuilder {
	private String redirect;
	private String view;
	private Map<String, Object> model = new HashMap<>();

	public DefaultViewBuilder() {
	}

	@Override
	public View build() {
		DefaultView view = new DefaultView();
		view.setRedirect(this.buildRedirect());
		view.setView(this.view);
		view.setModel(model);
		return view;
	}

	private String buildRedirect() {
		if (redirect == null || redirect.isEmpty())
			return null;

		StringBuilder url = new StringBuilder(128);
		url.append(redirect);
		if (!model.isEmpty()) {
			url.append("?");
			for (var entry : model.entrySet()) {
				url.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)).append("=");
				if (entry.getValue() != null) {
					url.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
				}
				url.append("&");
			}
			url.delete(url.length() - 1, url.length());
		}
		return url.toString();
	}

	@Override
	public DefaultViewBuilder setRedirect(String redirect) {
		this.redirect = redirect;
		return this;
	}

	@Override
	public DefaultViewBuilder setView(String view) {
		this.view = view;
		return this;
	}

	@Override
	public DefaultViewBuilder put(String key, Object value) {
		model.put(key, value);
		return this;
	}

	@Override
	public ViewBuilder putAll(Map<String, Object> map) {
		if (map != null && !map.isEmpty()) {
			model.putAll(map);
		}
		return this;
	}

	public DefaultViewBuilder remove(String key, Object value) {
		model.remove(key);
		return this;
	}


}
